package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbOrderDetailMapper;
import com.bwie.mapper.TbOrderRecordMapper;
import com.bwie.mapper.TbProdInfoMapper;
import com.bwie.poi.ExcelUtil;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.TbOrder;
import com.bwie.pojo.TbOrderDetail;
import com.bwie.pojo.TbOrderRecord;
import com.bwie.pojo.TbProdInfo;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.utils.R;
import com.bwie.utils.TokenUtils;
import com.bwie.vo.PageInfoVo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Lenovo
 * @description 针对表【tb_order(订单表)】的数据库操作Service实现
 * @createDate 2025-06-20 18:37:50
 */
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
        implements TbOrderService {

    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private TbProdInfoMapper tbProdInfoMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private TbOrderDetailMapper tbOrderDetailMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private TbOrderRecordMapper tbOrderRecordMapper;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public R getOrderList(PageInfoVo pageInfoVo) {
        String token = request.getHeader("token");
        if (token == null) {
            return R.error().setMsg("请先登录");
        }
        Integer userId = TokenUtils.getUserId(token);
        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(pageInfoVo.getKeyWord())){
            wrapper.lambda().like(TbOrder::getProdInfo,pageInfoVo.getKeyWord())
                    .or()
                    .like(TbOrder::getOrderId,pageInfoVo.getKeyWord());
        }
        if(pageInfoVo.getOrderStatus()!=null){
            wrapper.lambda().eq(TbOrder::getOrderStatus,pageInfoVo.getOrderStatus());
        }
        if(pageInfoVo.getTypeId()!=null){
            wrapper.lambda().eq(TbOrder::getOrderType,pageInfoVo.getTypeId());
        }

        wrapper.lambda().orderByDesc(TbOrder::getOrderId);

        Page<TbOrder> tbOrderPage = tbOrderMapper.selectPage(page, wrapper);

        for (TbOrder record : tbOrderPage.getRecords()) {
            List<String> imagesList = tbOrderMapper.getOrderImageList(record.getOrderId());
            ArrayList<String> imageList = new ArrayList<>();
            if(imagesList!=null && imagesList.size()>0){
                for (String s : imagesList) {
                    if(s!=null){
                        List<String> list = JSON.parseArray(s, String.class);
                        imageList.addAll(list);
                    }
                }
            }
            record.setImageList(imageList);
        }

        redisTemplate.opsForValue().set("order-list"+userId,JSON.toJSONString(tbOrderPage.getRecords()));

        return R.ok().setData(tbOrderPage);
    }

    @Override
    public R getProdInfo() {
        List<TbProdInfo> tbProdInfos = tbProdInfoMapper.selectList(null);
        return R.ok().setData(tbProdInfos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addOrder(List<TbProdInfo> tbProdInfoList) {
        String token = request.getHeader("token");
        if (token == null) {
            return R.error().setMsg("请先登录");
        }
        Integer userId = TokenUtils.getUserId(token);
        String userName = TokenUtils.getUserName(token);
        BigDecimal totalAmount = new BigDecimal("0");
        StringBuilder prodNames = new StringBuilder();

        RLock lock = redissonClient.getLock("order-lock");
        try {
            lock.lock();

            for (TbProdInfo tbProdInfo : tbProdInfoList) {
                TbProdInfo prodInfo = tbProdInfoMapper.selectById(tbProdInfo.getInfoId());
                if (tbProdInfo.getBuyNum() > prodInfo.getProdStock()) {
                    return R.error().setMsg("库存不足");
                }
                prodInfo.setProdStock(prodInfo.getProdStock() - tbProdInfo.getBuyNum());
                tbProdInfoMapper.updateById(prodInfo);

                totalAmount = totalAmount.add(tbProdInfo.getProdPrice().multiply(new BigDecimal(tbProdInfo.getBuyNum())));

                if (prodNames.length() > 0) {
                    prodNames.append(",");
                    prodNames.append(tbProdInfo.getProdName());
                } else {
                    prodNames.append(tbProdInfo.getProdName());
                }
            }
        } finally {
            lock.unlock();
        }


        TbOrder tbOrder = new TbOrder();

        //雪花算法生成订单编号
        long id = IdUtil.getSnowflake(1, 1).nextId();
        tbOrder.setOrderNo(id + "");
        tbOrder.setOrderType(1);
        tbOrder.setOrderStatus(0);
        tbOrder.setCreateTime(new Date());
        tbOrder.setUserId(userId);
        tbOrder.setOrderAmount(totalAmount);
        tbOrder.setProdInfo(prodNames.toString());
        tbOrder.setCreateBy(userName);
        tbOrderMapper.insert(tbOrder);

        for (TbProdInfo tbProdInfo : tbProdInfoList) {
            TbOrderDetail tbOrderDetail = new TbOrderDetail();
            tbOrderDetail.setOrderId(tbOrder.getOrderId());
            tbOrderDetail.setBuyNum(tbProdInfo.getBuyNum());
            tbOrderDetail.setProdId(tbProdInfo.getProdId());
            tbOrderDetail.setBuyPrice(tbProdInfo.getProdPrice());
            tbOrderDetail.setInfoId(tbProdInfo.getInfoId());
            tbOrderDetail.setCreateBy(userName);
            tbOrderDetail.setCreateTime(new Date());
            tbOrderDetailMapper.insert(tbOrderDetail);
        }

        TbOrderRecord tbOrderRecord = new TbOrderRecord();
        tbOrderRecord.setOrderId(tbOrder.getOrderId());
        tbOrderRecord.setOptRecord("用户创建订单");
        tbOrderRecord.setCreateTime(new Date());
        tbOrderRecord.setCreateBy(userName);
        tbOrderRecordMapper.insert(tbOrderRecord);
        return R.ok();
    }

    @Override
    public void excelOrderList(Integer userId) {
        ExcelUtil<TbOrder> excelUtil = new ExcelUtil<>(TbOrder.class);

        String s = redisTemplate.opsForValue().get("order-list" + userId);
        List<TbOrder> tbOrders = JSON.parseArray(s, TbOrder.class);

        excelUtil.exportExcel(response,tbOrders,"订单列表");



    }
}




